package com.platform.acl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.platform.acl.entity.Role;
import com.platform.acl.entity.User;
import com.platform.acl.entity.UserRole;
import com.platform.acl.mapper.UserMapper;
import com.platform.acl.mapper.UserRoleMapper;
import com.platform.acl.service.UserRoleService;
import com.platform.acl.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.platform.common_utils.MD5;
import com.platform.common_utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author CZF
 * @since 2022-02-23
 */
@Service("UserRoleService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserRoleService userRoleService;

    //注册用户(仅注册，默认授予用户学生的角色)
    @Override
    @Transactional
    public R addUser(User user) {
        User user1 = baseMapper.selectById(user.getId());
        if(user1 == null){ //如果该学生的学号不存在数据库中
            user.setPassword(MD5.encrypt(user.getPassword()));
            user.setLabPoint(-1);
            baseMapper.insert(user);

            //默认授予新用户学生的角色
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId("2");
            System.out.println(userRole);
            userRoleService.save(userRole);

            return R.ok();
        }else {
            return R.error().message("该学号已被注册！");
        }

    }

    @Override
    public User selectByUsername(String id) {
        //根据用户名查询数据库
        return baseMapper.selectOne(new QueryWrapper<User>().eq("id",id));
    }



    //excel批量插入user信息调用 TODO 默认密码 Zhku123456
    @Override
    public void addUserMess(User user) {
        user.setPassword(MD5.encrypt("Zhku123456"));
        baseMapper.insert(user);
    }
}
